with SDL.Mixer;
with SDL.Audio;
with Legend.Traces;
with Legend.Application;
package body Legend.Music is
   use SDL.Mixer;
   use type Interfaces.C.int;

   Current_Music : Music_ptr := null_Music_ptr;
   Current_Sound : Chunk_ptr := null_Chunk_ptr;

   procedure Play_Background_Music (Index : Uint16_t)
   is
      Path : String := Application.Config.Get("legend.music.path", "./music/");
   begin
      Trace_Log("play " & Traces.Image_Uint16(Index));
      if Index = No_Music then
         return;
      end if;
      declare
         S : String := Uint16_t'Image(Index + 101);
         Filename : String := Path & S(S'Last - 1 .. S'Last) & ".mid";
         new_music : Music_Ptr;
      begin
         new_music := Load_MUS(Filename);
         FadeInMusic(new_music, -1, 2000);
         if Current_Music /= null_Music_ptr then
            FreeMusic(Current_Music);
         end if;
         Current_Music := new_music;
      end;
   end Play_Background_Music;

   procedure Play_Attack_Sound (Index : Uint16_t)
   is
   begin
      Trace_Log("play attack sound " & Traces.Image_Uint16(Index));
      if Index = No_Sound then
         return;
      end if;
      declare
         S : String := Uint16_t'Image(Index + 100);
         Filename : String := JY_Path & "ATK" & S(S'Last - 1 .. S'Last) & ".WAV";
         sound    : Chunk_ptr := Load_WAV(Filename);
      begin
         PlayChannel(-1, sound, 0);
         if Current_Sound /= null_Chunk_ptr then
            FreeChunk(Current_Sound);
            Current_Sound := sound;
         end if;
      end;
   end Play_Attack_Sound;

   procedure Play_Effect_Sound (Index : Uint16_t)
   is
   begin
      Trace_Log("play effect sound " & Traces.Image_Uint16(Index));
      if Index = No_Sound then
         return;
      end if;
      declare
         S : String := Uint16_t'Image(Index + 100);
         Filename : String := JY_Path & "E" & S(S'Last - 1 .. S'Last) & ".WAV";
         sound    : Chunk_ptr := Load_WAV(Filename);
      begin
         PlayChannel(-1, sound, 0);
         if Current_Sound /= null_Chunk_ptr then
            FreeChunk(Current_Sound);
            Current_Sound := sound;
         end if;
      end;
   end Play_Effect_Sound;

   procedure Initialize
   is
      result : Interfaces.C.int := SDL.Mixer.OpenAudio(
         Frequency => 22050,
         Format    => SDL.Audio.AUDIO_S16,
         Channels  => 2,
         Chunksize => 4096);
   begin
      null;
   end Initialize;

   procedure Finalize
   is
   begin
      if Current_Music /= null_Music_ptr then
         FreeMusic(Current_Music);
      end if;
      if Current_Sound /= null_Chunk_ptr then
         FreeChunk(Current_Sound);
      end if;
      CloseAudio;
   end Finalize;

end Legend.Music;
